#!/usr/bin/env python
"""
找出模块导入搜索路径下最大的Python源码文件。
跳过已经访问过的目录，统一路径和大小写的格式以便使之正确匹配。
并在pprint打印结果中添加文件行数。
"""

import sys
import os
import pprint


def isWin():
    if sys.platform[:3] == 'win':
        return True
    else:
        False


def normpath(path):
    path = os.path.normpath(path)
    if isWin():
        return path, os.path.normcase(path)
    return path, None


def getPySizeList(curdir, filenames, trace=0):
    allsizes = []
    for eachfile in filenames:
        if eachfile.endswith('.py'):
            if trace > 1:
                print('\t' + eachfile)
            eachfile = os.path.join(curdir, eachfile)
            try:
                size = os.path.getsize(eachfile)
            except os.error:
                print('skipping', eachfile, sys.exc_info()[0])
            else:
                numlines = len(list(open(eachfile, 'rb')))
                allsizes.append((size, numlines, eachfile))
    return allsizes


def getAllSizes(trace=0):
    visited = []
    allsizes = []

    for libdir in sys.path:
        for curdir, subdir, files in os.walk(libdir):
            if trace > 0:
                print(curdir)
            curdir, dircase = normpath(curdir)
            if not isWin():
                dircase = curdir
            if dircase in visited:
                continue
            else:
                visited.append(dircase)
            allsizes.extend(getPySizeList(curdir, files, trace=trace))
    return allsizes


def showResult(allsizes):
    print('By size...')
    allsizes.sort()
    pprint.pprint(allsizes[:3])
    pprint.pprint(allsizes[-3:])

    print('By lines...')
    allsizes.sort(key=lambda x: x[1])
    pprint.pprint(allsizes[:3])
    pprint.pprint(allsizes[-3:])


def bigpyPath(trace=0, show=True):  # trace：1代表目录，2代表加上文件
    allsizes = getAllSizes(trace=trace)
    if show:
        showResult(allsizes)


if __name__ == '__main__':
    bigpyPath()
